import 'package:fluent_ui/fluent_ui.dart';

import '../../api/school_semester_api.dart';
import '../../api/semester_api.dart';
import '../../components/data_table.dart';
import '../../model/school_semester_model.dart';
import '../../model/semester_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class SchoolSemesterField {}

///学校学期:学年学期查询字段
enum SemesterQueryField implements SchoolSemesterField {
  title('标题'),
  status("状态");

  final String label;

  const SemesterQueryField(this.label);
}

///学校学期:查询字段
enum SchoolSemesterQueryField implements SchoolSemesterField {
  status('状态');

  final String label;

  const SchoolSemesterQueryField(this.label);
}

///学校学期:视图模型
class SchoolSemesterViewModel extends ChangeNotifier {
  ///学年学期查询字段
  final _querySemesterFields = <SemesterQueryField, TextEditingController>{
    for (var field in SemesterQueryField.values) field: TextEditingController(),
  };

  ///查询字段
  final _queryFields = <SchoolSemesterQueryField, TextEditingController>{
    for (var field in SchoolSemesterQueryField.values)
      field: TextEditingController(),
  };

  ///获取控制器
  TextEditingController? getController<T extends SchoolSemesterField>(
      final T field) {
    if (field is SemesterQueryField) {
      return _querySemesterFields[field];
    }
    if (field is SchoolSemesterQueryField) {
      return _queryFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SchoolSemesterField>(final T field) {
    final controller = getController(field);
    return controller?.text;
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final statusFuture = appDictData.buildOpts('status').then((statusOpts) {
        if (statusOpts.isNotEmpty) {
          _statusOpts.addAll(statusOpts);
        }
      });
      futures.add(statusFuture);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      //通知处理
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  ///清空学年学期字段
  void cleanSemesterFields() {
    for (var controller in _querySemesterFields.values) {
      controller.clear();
    }
  }

  ///清空查询字段值
  void cleanQueryFields() {
    for (var controller in _queryFields.values) {
      controller.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SemesterItemRes>();

  ///分页查询
  void query(final String schoolId) async {
    try {
      loading.showLoading();
      //状态
      final status = getFieldValue(SchoolSemesterQueryField.status);
      //分页查询
      final req = SchoolSemesterQueryReq(
        schoolId: schoolId,
        status: int.tryParse(status ?? '') ?? -1,
        index: queryModel.current,
        size: queryModel.size,
      );
      final res = await schoolSemesterApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('schoolSemesterApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///学年学期-查询模型
  final querySemesterModel = PageModel<SemesterItemRes>();

  ///分页查询
  void querySemesters() async {
    try {
      loading.showLoading();
      //状态
      final status = getFieldValue(SemesterQueryField.status);
      //分页查询
      final req = SemesterQueryReq(
        title: getFieldValue(SemesterQueryField.title) ?? '',
        status: int.tryParse(status ?? '') ?? -1,
        index: querySemesterModel.current,
        size: querySemesterModel.size,
      );
      //学年学期处理
      final res = await semesterApi.query(req);
      if (res.isSuccessed) {
        querySemesterModel.buildResData(res);
      }
      debugPrint('semesterApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///保存处理
  void onSaveHandler(
    final String schoolId,
    final List<String> semesters,
    final VoidCallback handler,
  ) async {
    try {
      loading.showLoading();
      final req = SchoolSemesterSaveReq(
        schoolId: schoolId,
        semesters: semesters,
        isAppend: true,
      );
      final res = await schoolSemesterApi.save(req);
      if (res.isSuccessed) {
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler({required final String schoolId, id}) async {
    if (schoolId.isEmpty || id.isEmpty) {
      return;
    }
    try {
      loading.showLoading();
      //删除
      final req = SchoolSemesterDeleteReq(
        schoolId: schoolId,
        semesterId: id,
      );
      final res = await schoolSemesterApi.delete(req);
      if (res.isSuccessed) {
        query(schoolId);
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
